import React, { useState } from 'react'
import { Button } from 'antd'
import './index.less'
import Wrapper from '../../components/Wrapper'
const ForwardRefPra = () => {
    let formRefs = {}
    let initData = [
        {
            partId: 1,
            name: '模块1',
        },
        {
            partId: 2,
            name: '模块2',
        }
    ]
    let [formData, setFormData] = useState(initData)
    const addModule = () => {
        formData.push(
            {
                partId: formData.length + 1,
                name: `模块${formData.length + 1}`
            }
        )
        let hhh = JSON.parse(JSON.stringify(formData))
        setFormData(hhh)
    }
    const verifyAllForm = () => {
        let formPromise = []
        for (let i in formRefs) {
            formPromise.push(
                new Promise((resolve, rejected) => {
                    formRefs[i].current.validateFields((err, values) => {
                        if (!err) {
                            resolve(values)
                        } else {
                            rejected(err)
                        }
                    })
                })
            )
        }
        return formPromise
    }
    const confirm = () => {
        Promise.all(verifyAllForm()).then((value) => {
            console.log(value, 'value')
        }).catch((err) => {
            console.log(err, 'err')
        })

    }
    const getForm = (partId) => {
        if (formRefs[partId]) {
            return formRefs[partId]
        }
        formRefs[partId] = React.createRef()
        return formRefs[partId]
    }

    return (
        <div className='flex2div'>
            <div className='height750 width300 padding24 bgwhite margin24'>
                <Button onClick={confirm}>确认</Button>
            </div>
            <div className='height750 width300 padding24 bgwhite margin24'>
                {formData.map((item) => {
                    let thisref = getForm(item.partId)
                    return <Wrapper
                        partId={item.partId}
                        name={item.name}
                        ref={thisref} />
                })}
            </div>
        </div>
    )
}

export default ForwardRefPra
